const container = document.getElementById('container');
const componentList = document.getElementById('componentList');

let activeComponentId = null;
let activeDragHandler = null;
let activeResizeHandler = null;

function resetAllStatus() {
  const items = container.querySelectorAll('.draggable');

  items.forEach(item => {
    item.className = 'draggable';
    const el = item.querySelector('.resizer');
    if (el) el.remove();
  });
}

function bindDragToActive() {
  if (activeDragHandler) {
    activeDragHandler.destroy();
    activeDragHandler = null;
  }
  if (!activeComponentId) return;

  const activeEl = container.querySelector(`#${activeComponentId}`);
  if (!activeEl) return;

  activeDragHandler = makeDraggable(activeEl);
}

function bindResizeToActive() {
  if (activeResizeHandler) {
    activeResizeHandler.destroy();
    activeResizeHandler = null;
  }
  if (!activeComponentId) return;

  const activeEl = container.querySelector(`#${activeComponentId}`);
  if (!activeEl) return;

  const resizer = activeEl.querySelector('.resizer');
  if (!resizer) return;

  activeResizeHandler = makeResizable(activeEl, resizer);
}

function getScale() {
  const containerRect = container.getBoundingClientRect();
  return container.offsetWidth / containerRect.width;
}

function makeDraggable(el) {
  let offsetX = 0, offsetY = 0;
  let scale = 1;

  function onStart(e) {
    if (e.target.classList.contains('resizer')) return;

    scale = getScale(); // 当前缩放值
    const rect = el.getBoundingClientRect();
    const touch = e.touches ? e.touches[0] : e;

    offsetX = (touch.clientX - rect.left) * scale;
    offsetY = (touch.clientY - rect.top) * scale;

    document.addEventListener(e.type.includes('touch') ? "touchmove" : "mousemove", onMove, { passive: false });
    document.addEventListener(e.type.includes('touch') ? "touchend" : "mouseup", onEnd);
  }

  function onMove(e) {
    e.preventDefault();

    const touch = e.touches ? e.touches[0] : e;
    const containerRect = container.getBoundingClientRect();
    const pointerX = (touch.clientX - containerRect.left) * scale;
    const pointerY = (touch.clientY - containerRect.top) * scale;

    let newLeft = pointerX - offsetX;
    let newTop = pointerY - offsetY;

    // 限制拖出容器边界
    newLeft = Math.max(0, Math.min(container.offsetWidth - el.offsetWidth - maxoffest, newLeft));
    newTop = Math.max(0, Math.min(container.offsetHeight - el.offsetHeight - maxoffest, newTop));

    el.style.left = `${newLeft}px`;
    el.style.top = `${newTop}px`;
  }

  function onEnd() {
    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onEnd);
    document.removeEventListener("touchmove", onMove);
    document.removeEventListener("touchend", onEnd);
  }

  el.addEventListener("mousedown", onStart);
  el.addEventListener("touchstart", onStart);

  return {
    destroy() {
      el.removeEventListener("mousedown", onStart);
      el.removeEventListener("touchstart", onStart);
      document.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseup", onEnd);
      document.removeEventListener("touchmove", onMove);
      document.removeEventListener("touchend", onEnd);
    }
  };
}

function makeResizable(el, handle) {
  let startX;
  let startWidth;
  let scale = 1;

  function onStart(e) {
    e.stopPropagation();
    scale = getScale(); // 当前缩放值
    const touch = e.touches ? e.touches[0] : e;
    startX = touch.clientX;
    startWidth = el.offsetWidth;

    document.addEventListener(e.type.includes('touch') ? "touchmove" : "mousemove", onMove, { passive: false });
    document.addEventListener(e.type.includes('touch') ? "touchend" : "mouseup", onEnd);
  }

  function onMove(e) {
    e.preventDefault();
    const touch = e.touches ? e.touches[0] : e;
    const deltaX = (touch.clientX - startX) * scale;

    let newWidth = startWidth + deltaX;
    if (newWidth < 40) newWidth = 40;

    const containerRect = container.getBoundingClientRect();
    const elRect = el.getBoundingClientRect();
    const maxWidth = ((containerRect.right - elRect.left) * scale) - maxoffest;

    if (newWidth > maxWidth) newWidth = maxWidth;

    el.style.width = `${newWidth}px`;
  }

  function onEnd() {
    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onEnd);
    document.removeEventListener("touchmove", onMove);
    document.removeEventListener("touchend", onEnd);
  }

  handle.addEventListener("mousedown", onStart);
  handle.addEventListener("touchstart", onStart);

  return {
    destroy() {
      handle.removeEventListener("mousedown", onStart);
      handle.removeEventListener("touchstart", onStart);
      document.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseup", onEnd);
      document.removeEventListener("touchmove", onMove);
      document.removeEventListener("touchend", onEnd);
    }
  };
}

function setActiveComponent(id) {
  resetAllStatus();
  activeComponentId = id;
  var div = container.querySelector(`#${activeComponentId}`);
  div.className = 'draggable active';
  const resizer = document.createElement('div');
  resizer.className = 'resizer';
  div.appendChild(resizer);
  bindDragToActive();
  bindResizeToActive();
}


// 测试新增插入文本函数
function insertText() {
  let inputText = prompt("请输入要插入的文本内容：", "新文本组件");
  if (inputText === null) return; // 取消
  inputText = inputText.trim();
  if (!inputText) {
    alert("文本不能为空！");
    return;
  }

  const id = 'txt_' + Date.now();

  const div = document.createElement('div');
  div.className = 'draggable active';
  div.style.left = '20%';
  div.style.top = '20%';
  div.style.width = '150px';
  div.dataset.type = 'text';
  div.id = id;
  div.textContent = inputText;
  container.appendChild(div);
  setActiveComponent(id);
}